package com.heima.xxljob.job;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jack
 * @data 2023 10:42
 */
@Component
@Slf4j
public class QuickStartJob {
    @Value("${xxl.job.executor.port}")
    private String port;

    //需求：给1万个用户发送1万张优惠券，每人1张
    @XxlJob("quickstartHandler")
    public void quickstart() {
        //分片套路：
        //a. 拿到分片总数
        int shardTotal = XxlJobHelper.getShardTotal();   //2
        //b. 拿到当前节点的分片索引
        int shardIndex = XxlJobHelper.getShardIndex();   //[0,1]

        //1. 拿到所有用户信息
        List<Integer> users = getUsers();
        //2. 遍历用户信息：给每个用户发放优惠券
        for (int i = 0; i < users.size(); i++) {
            //c: 当前任务由哪个分片执行通过算法来划分
            if (i % shardTotal == shardIndex) {
                Integer user = users.get(i);
                System.out.println(port + "给用户" + user + "发放了一张优惠券~~~");
            }
        }

    }

    //模拟查询数据库，得到1万个用户信息
    private List<Integer> getUsers() {
        List<Integer> userList = new ArrayList<>();
        for (int user = 1; user <= 10000; user++) {
            userList.add(user);
        }
        return userList;
    }
}
